package com.github.iogogogo.task;

import com.github.iogogogo.common.task.ScheduledTaskBean;
import com.github.iogogogo.common.task.ScheduledTaskService;
import com.github.iogogogo.entity.SysTaskEntity;
import com.github.iogogogo.repository.SysTaskRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by tao.zeng on 2021/3/30.
 */
@Slf4j
@Component
public class TaskRunner implements CommandLineRunner {

    @Autowired
    private ScheduledTaskService scheduledTaskService;

    @Autowired
    private SysTaskRepository taskRepository;

    @Override
    public void run(String... args) {

        // 读取数据库中状态为启动的任务，加载到调度队列中
        List<SysTaskEntity> entityList = taskRepository.findAll();

        log.info("load task running size:{}", entityList.size());

        if (!CollectionUtils.isEmpty(entityList)) {
            entityList.forEach(x -> {
                ScheduledTaskBean taskBean = new ScheduledTaskBean(x.getBeanName(), x.getMethodName(), x.getParam());
                scheduledTaskService.addCronTask(taskBean, x.getCron());
            });
        }
    }
}
